<template>
  <div>
    <n-space vertical size="large">
      <n-card>
        <n-statistic label="我的总积分" :value="totalPoints">
          <template #prefix>
            <n-icon size="32" color="#18A058">
              <TrophyOutline />
            </n-icon>
          </template>
        </n-statistic>
      </n-card>

      <n-card title="积分明细">
        <n-timeline>
          <n-timeline-item
            v-for="record in records"
            :key="record.id"
            :type="record.points > 0 ? 'success' : 'error'"
            :title="`${record.points > 0 ? '+' : ''}${record.points} 积分`"
            :content="record.description"
            :time="formatDate(record.createTime)"
          />
        </n-timeline>

        <n-empty v-if="!records.length" description="暂无积分记录" />

        <n-pagination
          v-if="records.length"
          v-model:page="pagination.page"
          :page-count="pagination.pageCount"
          style="margin-top: 20px; justify-content: center;"
          @update:page="loadRecords"
        />
      </n-card>
    </n-space>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { getUserPointRecords, getUserTotalPoints } from '@/api/point'
import { TrophyOutline } from '@vicons/ionicons5'

const userStore = useUserStore()

const totalPoints = ref(0)
const records = ref([])
const pagination = reactive({
  page: 1,
  pageSize: 10,
  pageCount: 1
})

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleString('zh-CN')
}

const loadRecords = async () => {
  try {
    const res = await getUserPointRecords(userStore.userId, {
      page: pagination.page,
      size: pagination.pageSize
    })
    records.value = res.data.records || []
    pagination.pageCount = res.data.pages || 1
  } catch (error) {
    console.error('加载积分记录失败:', error)
  }
}

const loadTotalPoints = async () => {
  try {
    const res = await getUserTotalPoints(userStore.userId)
    totalPoints.value = res.data || 0
  } catch (error) {
    console.error('加载总积分失败:', error)
  }
}

onMounted(() => {
  loadTotalPoints()
  loadRecords()
})
</script>

